﻿using UnityEngine;
using System.Collections;
using Boo.Lang;
using System;

namespace Memo.Electricity.Engine
{
	public class MemoBehaviour : MonoBehaviour
	{
		#region 协程模块

		private List<WaitForCoroutine> mCoroutines = new List<WaitForCoroutine>();
		private int mNextCoroutineClearCount = 10;

		public new WaitForCoroutine StartCoroutine(IEnumerator iter)
		{
			WaitForCoroutine wait = CCoroutineMgr.Inst.StartCoroutine(iter);
			mCoroutines.Add(wait);
			if(mCoroutines.Count >= mNextCoroutineClearCount)
			{
				ClearCoroutines();
				mNextTickClearCount = mCoroutines.Count * 2 + 1;
			}
			return wait;
		}

		private void ClearCoroutines()
		{
			mCoroutines.RemoveAll((WaitForCoroutine wait) => wait.IsReady());
		}

		#endregion

		#region Tick模块

		private List<CTick> mTicks = new List<CTick>();
		private int mNextTickClearCount = 10;

		public void RegisterTick(Action func, float intervel, ETickType tickType = ETickType.Loop)
		{
			mTicks.Add(CTickMgr.Inst.RegisterTick(func, intervel, tickType));
			if (mTicks.Count > mNextTickClearCount)
			{
				ClearTicks();
				mNextTickClearCount = mTicks.Count * 2 + 1;
			}
		}

		public void RegisterOnce(Action func, float intervel)
		{
			RegisterTick(func, intervel, ETickType.Once);
		}

		public void DeregisterTick(CTick tick)
		{
			if (!mTicks.Contains(tick))
				return;
			mTicks.Remove(tick);
			tick.Cancle();
		}

		private void ClearTicks()
		{
			mTicks.RemoveAll((CTick tick) => !tick.IsValid);
		}

		#endregion

		#region 生命周期函数

		protected virtual void OnDestroy()
		{
			foreach (var wait in mCoroutines)
				CCoroutineMgr.Inst?.StopCoroutine(wait);

			foreach (var tick in mTicks)
				CTickMgr.Inst?.DeregisterTick(tick);
		}

		#endregion

	}
}